//
//  ClassifyViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/7/24.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit
import DZNEmptyDataSet

/// 分类首页
class ClassifyViewController: BaseViewController {
    
    var seleIndex = 0
    
    var segmentIndex = 0
    
    var goodsTypeArray = [GoodsTypeListModel]()
    
    var dataArray = [SiteGoodsModel]()
    
    var pageNum = 1
    
    var isPromotion = 0 // 是否直看促销  0否 1是
    
    var sortType = 0 //排序方式  0综合排序 1购买量排序 2价格升序 3价格倒序
    
    var lastGoodsSmallId = 0
    
    lazy var fliterView:ClassifyRankContentView = {
       let view = ClassifyRankContentView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: UIScreen.ScreenHeight))
        UIApplication.shared.keyWindow?.addSubview(view)
        view.backSeleIndex = { [weak self] (index) in
            self?.sortType = index.0
            self?.rightFilterLabel.text = index.1
            self?.getGoodsList(goodsSmallId: (self?.lastGoodsSmallId)!)
        }
        return view
    }()
    
    
    @IBOutlet weak var navHeight: NSLayoutConstraint!
    @IBOutlet weak var topBaseView: UIView!
    @IBOutlet weak var menuBaseView: UIView!
    @IBOutlet weak var leftFilterButton: UIButton!
    @IBOutlet weak var rightFilterLabel: UILabel!
    
    @IBOutlet weak var leftTableView: UITableView!
    @IBOutlet weak var rightTableView: UITableView!
    
    
    var pageFilterTitleView:FSSegmentTitleView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.view.backgroundColor = UIColor.white
        changeStyle()
        NotificationCenter.default.addObserver(self, selector: #selector(logined), name: NSNotification.Name(rawValue: "logined"), object: nil)
        self.rightTableView.emptyDataSetSource = self
        self.rightTableView.emptyDataSetDelegate = self
    }
    
    @objc func logined(){
        self.pageNum = 1
        self.segmentIndex = 0
        self.getGoodsTypeList()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: true)
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: 综合排序
    @IBAction func rightFilterButtonClick(_ sender: UIButton) {
        self.fliterView.show()
    }
    
    // MARK:只看促销
    @IBAction func onlyPromotionButtonClick(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        self.isPromotion = sender.isSelected ? 1 : 0
        self.getGoodsList(goodsSmallId: self.lastGoodsSmallId)
    }
    
    
    // MARK: 跳转搜索
    @IBAction func search(_ sender: UIButton) {
        let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "SearchViewController") as! SearchViewController
        ctrl.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(ctrl, animated: true)
    }
    
    // MARK:获取一级和二级分类
    func getGoodsTypeList(){
        HttpRequest.requestData(.post, URLString: Api.goodsTypeList.rawValue, parameters: nil) { (result) in
            if result["msg"] as! String == "success"{
                if let array = [GoodsTypeListModel].deserialize(from: result["data"] as? [Any]) as? [GoodsTypeListModel]{
                    self.goodsTypeArray = array
                    
                    var titleArray = [String]()
                    for model in array {
                        titleArray.append(model.name)
                    }
                    self.initSegmentView(titleArray: titleArray)
                    
                    self.leftTableView.reloadData()
                    self.getGoodsList(goodsSmallId: (self.goodsTypeArray.first?.smallTypes.first?.id)!)
                    
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    func getGoodsList(goodsSmallId:Int){
        self.lastGoodsSmallId = goodsSmallId
        let parametr:postParameters = ["goodsSmallId":goodsSmallId,"isPromotion":self.isPromotion,"sortType":self.sortType,"pageNum":self.pageNum,"pageSize":10]
        HttpRequest.requestData(.post, URLString: Api.goodsTypeGoods.rawValue, parameters:parametr ) { (result) in
            if result["msg"] as! String == "success"{
                if let array = [SiteGoodsModel].deserialize(from: result["data"] as? [Any]) as? [SiteGoodsModel] {
                    self.dataArray = array
                    self.rightTableView.reloadData()
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
}

extension ClassifyViewController:FSSegmentTitleViewDelegate{
    
    fileprivate func changeStyle(){
        self.topBaseView.setShadow(color: "#000000,", offset: CGSize.init(width: 0, height: 1), radius: 8, opacity: 0.1)
        self.navHeight.constant = Utils.isIphoneX() ? 88 : 64
        
        
        let viewLine = UIView.init(frame: CGRect.init(x: 0, y: 44.5, width: UIScreen.ScreenWidth, height: 0.5))
        viewLine.backgroundColor = UIColor.viewLineColor
        self.menuBaseView.addSubview(viewLine)
        
        self.rightTableView.rowHeight = 110
        self.rightTableView.separatorColor = UIColor.viewLineColor
        self.leftTableView.rowHeight = 60
        self.leftTableView.showsVerticalScrollIndicator = false
        self.rightTableView.showsVerticalScrollIndicator = false
        self.rightTableView.tableFooterView = UIView()
        
        getGoodsTypeList()
        
    }
    
    func initSegmentView(titleArray:[String]){
        if self.pageFilterTitleView != nil {
            self.pageFilterTitleView.removeFromSuperview()
        }
        self.pageFilterTitleView = FSSegmentTitleView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: 45), titles: titleArray, delegate: self, indicatorType: FSIndicatorTypeEqualTitle)
        self.pageFilterTitleView.itemMargin = 33
        self.pageFilterTitleView.selectIndex = 0
        self.pageFilterTitleView.titleFont = UIFont.systemFont(ofSize: 13)
        self.pageFilterTitleView.titleSelectFont = UIFont.boldSystemFont(ofSize: 13)
        self.pageFilterTitleView.titleNormalColor = UIColor.init(hexColor: "#333333")
        self.pageFilterTitleView.titleSelectColor = UIColor.init(hexColor: "#f7c201")
        self.pageFilterTitleView.indicatorColor = UIColor.init(hexColor: "f7c201")
        self.pageFilterTitleView.indicatorExtension = 5
        self.menuBaseView.addSubview(self.pageFilterTitleView)
    }
    
    func fsSegmentTitleView(_ titleView: FSSegmentTitleView!, start startIndex: Int, end endIndex: Int) {
        self.segmentIndex = endIndex
        self.seleIndex = 0
        self.leftTableView.reloadData()
        if self.goodsTypeArray[segmentIndex].smallTypes.count == 0 {
            self.dataArray.removeAll()
            self.rightTableView.reloadData()
            return
        }
        self.getGoodsList(goodsSmallId: (self.goodsTypeArray[segmentIndex].smallTypes.first?.id)!)
    }
    
}

extension ClassifyViewController:UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == self.leftTableView {
            return self.goodsTypeArray.count == 0 ? 0 : self.goodsTypeArray[segmentIndex].smallTypes.count
        }else{
            return self.dataArray.count
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if tableView == self.leftTableView {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ClassifyLeftTableViewCell") as! ClassifyLeftTableViewCell
            cell.goodsName.text = self.goodsTypeArray[self.segmentIndex].smallTypes[indexPath.row].name
            if indexPath.row == self.seleIndex {
                cell.selectedStyle()
            }else{
                cell.normalStyle()
            }
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "ClassifyRightTableViewCell") as! ClassifyRightTableViewCell
            cell.reload(withModel: self.dataArray[indexPath.row])
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if tableView  == self.leftTableView {
            let lastCell = tableView.cellForRow(at: IndexPath.init(row: self.seleIndex, section: 0)) as! ClassifyLeftTableViewCell
            lastCell.normalStyle()
            self.seleIndex = indexPath.row
            let cell = tableView.cellForRow(at: IndexPath.init(row: self.seleIndex, section: 0)) as! ClassifyLeftTableViewCell
            cell.selectedStyle()
            self.getGoodsList(goodsSmallId: (self.goodsTypeArray[segmentIndex].smallTypes[indexPath.row].id))
        }else {
            let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "GoodsDetailViewController") as! GoodsDetailViewController
            ctrl.hidesBottomBarWhenPushed = true
            let model = self.dataArray[indexPath.row]
            ctrl.goodsID = model.id
            if model.isDiscount == 1 {
                ctrl.type = .discount
            }
            self.navigationController?.pushViewController(ctrl, animated: true)
        }
    }
}

extension ClassifyViewController:DZNEmptyDataSetSource,DZNEmptyDataSetDelegate{
    
    func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
        let str = "敬请期待~"
        let attribute = NSMutableAttributedString.init(string: str)
        attribute.addAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 14),
                                 NSAttributedStringKey.foregroundColor:UIColor.init(hexColor: "666666")], range: NSRange.init(location: 0, length: str.count))
        
        return attribute
    }
    
    func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        return UIImage.init(named: "img_Defaultheadimage")
    }
    
}


















